package com.ev.framework.aspect;

import com.ev.common.service.DataService;
import com.ev.framework.annotation.RecoverRemoveData;
import com.ev.framework.utils.StringUtils;
import com.google.common.collect.Lists;
import org.apache.commons.lang.math.NumberUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.*;
/**
 * 逻辑删除切片
 */
@Aspect
@Component
public class RecoverRemoveDataAspect {
    @Autowired
    DataService dataService;

    /**
     * 设置操作恢复删除数据切入点 记录操作恢复删除数据 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.ev.framework.annotation.RecoverRemoveData)")
    public void recoverPointCut() {
    }


    /**
     * 正常返回通知，拦截用户操作恢复删除数据，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "recoverPointCut()", returning = "keys")
    public void updateRemoveData(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            RecoverRemoveData recoverRemoveData = method.getAnnotation(RecoverRemoveData.class);
            String tableName = null;
            String columnName = null;
            String columnValue = null;
            if (recoverRemoveData != null) {
                tableName = recoverRemoveData.tableName();
                columnName = recoverRemoveData.columnName();
                columnValue = recoverRemoveData.columnValue();
            }
            // 请求的参数
            Map<String, String[]> rtnMap = request.getParameterMap();
            List<Long> ids = Lists.newArrayList();
            if (rtnMap.size() == 0) {
                // TODO requestBody 传参 展现形式未知 待存在再进行修改

//                params = JSON.toJSONString(joinPoint.getArgs());
            } else {
                // requestParam 传参形式：1,2,3
                // 将参数所在的数组转换成json
                String[] strings = rtnMap.values().stream().findFirst().orElse(new String[0]);
                if (strings.length > 0) {
                    for (String string : strings) {
                        String[] idsToArray = string.split(",");
                        if (idsToArray.length == 0) {
                            return;
                        }
                        for (String s : idsToArray) {
                            if (NumberUtils.isNumber(s)) {
                                ids.add(Long.parseLong(s));
                            }
                        }
                    }

                }
            }

            if (StringUtils.isBlank(tableName) || StringUtils.isBlank(columnName) || ids.size() == 0) {
                return;
            }

            dataService.updateData(ids, tableName, columnName, columnValue);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
